package com.runvp.service.auth.service;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.model.auth.LoginUser;
import com.runvp.common.util.auth.PlatConstant;
import com.runvp.common.util.auth.SecurityUtils;
import com.runvp.common.utils.IpUtils;
import com.runvp.common.utils.ServletUtils;
import com.runvp.common.utils.StringUtils;
import com.runvp.common.utils.uuid.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author xkk update
 */
@Slf4j
@Component
public class TokenService {
    @Autowired
    private RedisCache redisService;


    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        // 生成token
        String token = IdUtils.fastSimpleUUID();
        loginUser.setToken(token);
        loginUser.setIpAddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        refreshToken(loginUser);
        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", PlatConstant.TOKEN_EXPIRE_TIME);
        String tokenKey = SecurityUtils.buildTokenKey(loginUser.getUserBO().getOpenId(), loginUser.getUserBO().getType());
        String oldToken = redisService.getCacheObject(tokenKey);
        if (StringUtils.isNotBlank(oldToken)) {
            Object o = redisService.getCacheObject(oldToken);
            log.info("旧token:{}", JSONObject.toJSONString(o));
            //清理上次登录token
            boolean result = redisService.deleteObject(oldToken);
            log.info("清理旧token：{}", result);
        }
        redisService.setCacheObject(tokenKey, SecurityUtils.buildToken(token), PlatConstant.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String userKey = SecurityUtils.buildToken(token);
            LoginUser user = redisService.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = SecurityUtils.buildToken(token);
            redisService.deleteObject(userKey);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + PlatConstant.TOKEN_EXPIRE_TIME);
        // 根据uuid将loginUser缓存
        String userKey = SecurityUtils.buildToken(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, PlatConstant.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
    }

}